package com.ja.openchat.views;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.allen.library.SuperButton;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.google.gson.JsonObject;
import com.ja.openchat.R;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.user.AbsGroupInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.DensityUtil;
import com.zy.openchat.util.glide.GlideApp;

import java.util.Map;

public class UserAvatarView extends FrameLayout implements TgResultBlock<UserInfo> {

    ImageView portraitImageView;
    SuperButton portraitTextView;

    public UserAvatarView(@NonNull Context context) {
        super(context);
        init(context, null);
    }

    public UserAvatarView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public UserAvatarView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private int roundRadius = 10;
    private float avatarTextSize = 16;

    private void init(Context context, AttributeSet attrs) {
        if (attrs != null) {
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.UserAvatarView);
            roundRadius = typedArray.getDimensionPixelSize(R.styleable.UserAvatarView_avatarRoundRadius, 10);
            avatarTextSize = typedArray.getFloat(R.styleable.UserAvatarView_avatarTextSize, 16);
            typedArray.recycle();
        }
        inflate(context, R.layout.view_avatar, this);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        portraitImageView = findViewById(R.id.portraitImageView);
        portraitTextView = findViewById(R.id.portraitTextView);
        portraitTextView.setEnabled(false);
        portraitTextView.setClickable(false);
        portraitTextView.setTextSize(avatarTextSize);
    }

    public void showUser(UserInfo userInfo, int roundRadius) {
        if (userInfo != null) {
            if (!userInfo.isDeleteAccount()&&userInfo.profile_photo != null && userInfo.profile_photo.isSmallPhotoDownloaded()) {
                if (portraitImageView != null) {
                    portraitImageView.setVisibility(View.VISIBLE);
                    GlideApp
                            .with(getContext())
                            .load(userInfo.profile_photo.small.local.path)
                            .transforms(new CenterCrop(), new RoundedCorners(roundRadius))
                            .placeholder(R.mipmap.avatar_def)
                            .into(portraitImageView);
                }
                if (portraitTextView != null) {
                    portraitTextView.setVisibility(View.GONE);
                }

            } else {
                if (!userInfo.isDeleteAccount()&&userInfo.profile_photo != null) {//头像未下载，进行下载
                    TelegramManager.getTelegramManager().downloadFile("" + userInfo.id, userInfo.profile_photo.fileSmallId(), 0, TelegramManager.FileType.FileType_Photo);
                }
                if (portraitTextView != null && !TextUtils.isEmpty(userInfo.displayName())) {
                    portraitTextView.setVisibility(View.VISIBLE);
                    portraitImageView.setVisibility(View.GONE);
                    portraitTextView.setShapeCornersRadius(DensityUtil.px2dip(roundRadius));
                    decoPortrait(userInfo.displayName().toUpperCase().charAt(0), portraitTextView);
                }
                if (userInfo.id == 777000) {
                    portraitTextView.setVisibility(View.GONE);
                    portraitImageView.setVisibility(View.VISIBLE);
                    portraitImageView.setImageResource(R.mipmap.notice);
                } else {
                    portraitImageView.setImageResource(R.mipmap.avatar_def);
                }

            }
        }
    }

    public void showDefault() {
        portraitImageView.setVisibility(View.VISIBLE);
        GlideApp
                .with(getContext())
                .load("")
                .transforms(new CenterCrop(), new RoundedCorners(roundRadius))
                .placeholder(R.mipmap.avatar_def)
                .into(portraitImageView);
        portraitTextView.setVisibility(View.GONE);
    }

    public void showUser(UserInfo userInfo) {
        showUser(userInfo, roundRadius);
    }

    public void showUser(long userId){
        UserInfo userInfo = UserInfo.getUserInfo(userId);
        if(userInfo!=null){
            showUser(userInfo);
        }else{
            TelegramManager.getTelegramManager().getUserSimpleInfo(userId,this);
        }
    }

    @Override
    public void onResult(Map<String, Object> request, JsonObject response, UserInfo obj) {
        showUser(obj);
    }

    @Override
    public void onTimeout(Map<String, Object> request) {

    }

    public void showGroup(AbsGroupInfo chatInfo) {
        showGroup(chatInfo, roundRadius);
    }

    public void showGroup(AbsGroupInfo chatInfo, int roundRadius) {
        if (chatInfo != null) {
            if (chatInfo.photo() != null && chatInfo.photo().isSmallPhotoDownloaded()) {
                if (portraitImageView != null) {
                    portraitImageView.setVisibility(View.VISIBLE);
                    GlideApp
                            .with(getContext())
                            .load(chatInfo.photo().localSmallPath())
                            .transforms(new CenterCrop(), new RoundedCorners(roundRadius))
                            .placeholder(R.mipmap.avatar_def_group)
                            .into(portraitImageView);
                }
                if (portraitTextView != null) {
                    portraitTextView.setVisibility(View.GONE);
                }

            } else {
                if (chatInfo.photo() != null) {//头像未下载，进行下载
                    TelegramManager.getTelegramManager().downloadFile("" + chatInfo.chatId(), chatInfo.photo().fileSmallId(), 0, TelegramManager.FileType.FileType_Group_Photo);
                }
                if (portraitTextView != null && !TextUtils.isEmpty(chatInfo.title())) {
                    portraitTextView.setVisibility(View.VISIBLE);
                    portraitTextView.setShapeCornersRadius(DensityUtil.px2dip(roundRadius));
                    decoPortrait(chatInfo.title().toUpperCase().charAt(0), portraitTextView);
                }
                if (portraitImageView != null) {
                    portraitImageView.setImageResource(R.mipmap.avatar_def_group);
                }

            }
        }
    }

    public void showName(String name) {
        showName(name, roundRadius);
    }

    public void showName(String name, int roundRadius) {
        if (portraitTextView != null && !TextUtils.isEmpty(name)) {
            portraitTextView.setVisibility(View.VISIBLE);
            portraitTextView.setShapeCornersRadius(DensityUtil.px2dip(roundRadius));
            decoPortrait(name.toUpperCase().charAt(0), portraitTextView);
        }
        if (portraitImageView != null) {
            portraitImageView.setVisibility(View.GONE);
        }
    }

    public void showImage(int src) {
        if (portraitImageView != null) {
            portraitImageView.setVisibility(View.VISIBLE);
            portraitImageView.setImageResource(src);
        }
        if (portraitTextView != null) {
            portraitTextView.setVisibility(View.GONE);
        }
    }

    public void setTextSize(int size) {
        if (portraitTextView != null) {
            portraitTextView.setTextSize(size);
        }
    }

    private void decoPortrait(char text, SuperButton tx) {
        int index = text % 7;
        String startColor, endColor;
        switch (index) {
            case 1:
                startColor = getResources().getString(R.string.header_bg1_start);
                endColor = getResources().getString(R.string.header_bg1_end);
                break;
            case 2:
                startColor = getResources().getString(R.string.header_bg2_start);
                endColor = getResources().getString(R.string.header_bg2_end);
                break;
            case 3:
                startColor = getResources().getString(R.string.header_bg3_start);
                endColor = getResources().getString(R.string.header_bg3_end);
                break;
            case 4:
                startColor = getResources().getString(R.string.header_bg4_start);
                endColor = getResources().getString(R.string.header_bg4_end);
                break;
            case 5:
                startColor = getResources().getString(R.string.header_bg5_start);
                endColor = getResources().getString(R.string.header_bg5_end);
                break;
            case 6:
                startColor = getResources().getString(R.string.header_bg6_start);
                endColor = getResources().getString(R.string.header_bg6_end);
                break;
            default:
                startColor = getResources().getString(R.string.header_bg7_start);
                endColor = getResources().getString(R.string.header_bg7_end);
                break;
        }
        tx.setText(String.valueOf(text));
        tx.setShapeGradientStartColor(Color.parseColor(endColor))
                .setShapeGradientStartColor(Color.parseColor(startColor))
                .setUseShape();

    }

}
